/**
 * Created by JustinChow on 2016/11/7.
 */

"use strict";

const Logger = require("pomelo-logger").getLogger("GameObjectHandler", __filename);

function GameObjectHandler(gameServer, collisionHandler){

    // PlayerTracker
    this.toUpdate = [];

    // All Game Objects
    this.gameObjects = [];

    this.gameServer = gameServer;
    this.collisionHandler = collisionHandler;
}

module.exports = GameObjectHandler;

GameObjectHandler.prototype.update = function () {
    var time = new Date();

    while (this.toUpdate.length > 0) {
        var client = this.toUpdate[0];
        this.toUpdate.shift();
        if (!client || client.fullyDisconnected) continue;

        if (client.player !== null) {
            // Todo Calc Collide: if (this.collisionHandler.collide(??))

            // Todo Calc Collision
            for (let vnid = 0, vnlen = client.visibleNodes.length; vnid < vnlen; vnid++) {
                if (!client.visibleNodes[vnid]) continue;
                if (this.gameServer.collisionHandler.collide(client.player, client.visibleNodes[vnid])){
                    client.collide = true;
                    Logger.warn("Collide [ %j %j ] With [ %j %j ]", client.player.position, client.player.collision, client.visibleNodes[vnid].position, client.visibleNodes[vnid].collision);
                }
            }

            if (!client.collide) {
                // move
                client.player.moveEngineTick();
                // move player in the quad-tree
                this.gameServer.quadTree.update(client.player);
            }

            // move
            // client.player.moveEngineTick();
            // // move player in the quad-tree
            // this.gameServer.quadTree.update(client.player);
        }

        if (client.propsHandler) client.propsHandler.update();

        setTimeout(function () {
            if (this.fullyDisconnected) return;
            this.gameServer.gameObjectHandler.toUpdate.push(this);
        }.bind(client), 25);
    }

    this.gameServer.tickGameObjectHandler = new Date() - time;
};

GameObjectHandler.prototype.debug = function () {
    Logger.debug("This Game Server Config [ %j ]", this.gameServer.config);
};
